package com.loozb;

import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.util.Progressable;
import org.junit.Test;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URL;

/**
 * Created by chuan on 2019-4-17.
 */
public class URLCat {
    static {
        URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory());
    }

    private String hdfs = "hdfs://192.168.1.109/";

    /**
     * 上传文件到hdfs
     */
    @Test
    public void test0() throws Exception{
        InputStream inputStream = new BufferedInputStream(new FileInputStream("D:\\hello.txt"));
        String dfs = hdfs + "abcd/ab/hello.txt";
        Configuration configuration = new Configuration();
        FileSystem fs = FileSystem.get(URI.create(dfs), configuration);
        OutputStream out = fs.create(new Path(dfs), new Progressable() {
            public void progress() {
                System.out.println(".");
            }
        });
        IOUtils.copyBytes(inputStream, out, 4096, true);

    }

    /**
     * 读取hdfs里的文件
     */
    @Test
    public void test1() {
        InputStream inputStream = null;

        try {
            inputStream = new URL(hdfs + "user/root/hello.txt").openStream();
            IOUtils.copyBytes(inputStream, System.out, 4096, false);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeStream(inputStream);
        }
    }

    /**
     * 列出文件
     * @throws Exception
     */
    @Test
    public void listState() throws Exception{
        String uri1 = hdfs;
        String uri2 = hdfs + "/user/root";

        Configuration configuration = new Configuration();
        FileSystem fileSystem = FileSystem.get(URI.create(uri1), configuration);

        Path[] paths = new Path[2];
        paths[0] = new Path(uri1);
        paths[1] = new Path(uri2);

        FileStatus[] status = fileSystem.listStatus(paths);
        Path[] listedPath = FileUtil.stat2Paths(status);
        for (Path p: listedPath) {
            System.out.println(p);
        }
    }

    /**
     * 删除文件
     * @throws Exception
     */
    @Test
    public void deleteFile() throws Exception{
        String uri2 = hdfs + "user/root/hello.txt";

        Configuration configuration = new Configuration();
        FileSystem fileSystem = FileSystem.get(URI.create(uri2), configuration);
        boolean f = fileSystem.delete(new Path(uri2), false);
        System.out.println(f);
    }
}
